package com.dwjm.shop.HYZ.goods;

import com.google.gson.Gson;
import com.dwjm.shop.utils.CommonResult;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/goodsDetail")
public class GoodsDetailHandler extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 统一编码设置
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        try {
            // 获取请求参数
            String idParam = req.getParameter("id");
            int goodsId = Integer.parseInt(idParam);
            // 调用DAO层
            GoodsDao goodsDao = new GoodsDaoImpl();
            Goods goods = goodsDao.getDetail(goodsId);
            // 构建响应结果
            CommonResult<Goods> result = goods != null ?
                    CommonResult.success(goods) :
                    CommonResult.fail(404, "商品不存在");
            // JSON序列化
            resp.getWriter().write(new Gson().toJson(result));

        } catch (NumberFormatException e) {
            resp.getWriter().write(new Gson().toJson(
                    CommonResult.fail(400, "参数格式错误")
            ));
        } catch (Exception e) {
            resp.getWriter().write(new Gson().toJson(
                    CommonResult.fail(500, "服务器内部错误")
            ));
        }
    }
}
